package com.wyb.fastdfs.service;

import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;

import lombok.extern.slf4j.Slf4j;

/**
 * @Author:wangyibo
 * @Date 2021年8月11日
 * @Version:1.0
 * @Description:TODO
 */
@Service
@Slf4j
public class DownloadService {

	@Autowired
	private FastFileStorageClient fastFileStorageClient;

	@Value("${upload.base-url}")
	public String baseUrl;

	public void downloadFile(String path, HttpServletResponse response) throws IOException {
		// http://fastdfs.com:8888/group1/M00/00/00/wKgKamETLNmATg9vB2jRkFweTSk792.exe
		String subString = StringUtils.substringAfter(path, baseUrl);
		String groupName = StringUtils.substring(subString, 0, 6);
		log.info("========" + groupName);
		String urlName = StringUtils.substringAfter(path, groupName + "/");
		log.info(urlName);
		byte[] bytes = fastFileStorageClient.downloadFile(groupName, urlName, new DownloadByteArray());
		try {
			response.addHeader("Content-disposition", "attachment;filename=" + new String(urlName.getBytes()));
			OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
			response.setContentType("application/vnd.ms-excel;charset=UTF-8");
			response.setContentType("application/x-msdownload");
			toClient.write(bytes);
			toClient.flush();
			toClient.close();
			System.out.println("下载成功");
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
//		try {
//			FileOutputStream stream = new FileOutputStream(StringUtils.substringAfterLast(urlName, "/"));
//			try {
//				stream.write(bytes);
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//		} catch (FileNotFoundException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
	}

}
